<template>
  <div class="_comment-action">

    <div v-show="!active" class="_comment-action__kits">

      <div class="_comment-action__kits-tip" @click="showInput">
        <img @click.stop="handleClick" :src="user.avatarIM" alt="" srcset="">
        <template v-if="content">{{ content }}</template>
        <template v-else>说点什么吧</template>
      </div>
    </div>
    <div v-show="active" class="_comment-action__input">
      <van-field @keyup.enter.native="send" ref="inputRef" v-model.trim="content" :maxlength="50" placeholder="说点什么吧..."
        @blur="blur" />
      <van-button size="small" type="info" @touchstart="send"> 发送 </van-button>
    </div>
    <u-popup :round="8" :show="editInfoModal" v-if="userData" mode="center" :closeOnClickOverlay='false'>
      <div class="edit-info">
        <div class="edit-info-title">编辑用户信息</div>
        <div class="edit-info-item">
          <div>头像：</div>
          <div @click="choosePic" class="flex-center"><img :src="userData.avatar" alt=""> <i class="right-icon"></i>
          </div>
        </div>
        <div class="edit-info-item">
          <div>昵称：</div>
          <div class="flex-center"> <u--input inputAlign="right" v-model="userData.nickname" border="none"></u--input><i
              class="right-icon"></i></div>
        </div>
        <div class="edit-info-action">
          <span @tap='userData = null; editInfoModal = false'>取消</span>
          <span @tap="handleEdit">确定</span>
        </div>
      </div>
    </u-popup>
  </div>
</template>

<script>
import liveInfo from '@/mixins/liveInfo';
import liveSetting from '@/mixins/liveSetting';
import { mapState } from 'vuex';
import { formatUsername } from './helper';
import { Button as vanButton, Field as vanField } from 'vant';
import EventBus from '@/utils/eventBus'
import { updateUser } from '@/api/user'
import {
  txCosUpload
} from '@/utils/txCosUpload'
import { setTimeout } from 'core-js';
const preWindowHeight = window.innerHeight;

export default {
  components: {
    vanButton,
    vanField
  },
  mixins: [liveInfo, liveSetting],
  data() {
    return {
      userData: null,
      editInfoModal: false,
      active: false,
      content: '',
      replyUserId: '',
      replyUsername: '',
      isFixedVest: false,
      fixedVest: null
    };
  },
  computed: {
    ...mapState({
      user(state) {
        return state.user;
      },
    }),
  },
  mounted() {
    EventBus.$on(EventBus.reply, (item) => {
      this.active = true;
      this.replyUserId = item.userId;
      this.replyUsername = item.nickname || item.username;
      this.content = `@${item.nickname || item.username} `
    })
    window.addEventListener('resize', this.keyboardWatch);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.keyboardWatch);
  },
  methods: {
    choosePic() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const file = res.tempFiles[0];
          const params = {
            scene: 'business_avatar'
          }
          txCosUpload(file, params, (progressData) => {
            // 实现进度条，目前没用到
          },).then(fileRes => {
            uni.showToast({
              title: '上传成功',
              icon: 'none',
              duration: 1500
            })
            this.userData.avatar = fileRes.fileUrl

          })
        },
        fail: (res) => {
          console.log('上传图片fail', res)
        }
      });
    },
    async handleEdit() {
      console.log(this.user)
      await updateUser({
        avatar: this.userData.avatar,
        nickname: this.userData.nickname,
        birthday: this.user.userInfo.birthday,
        email: this.user.email,
        sex: this.user.userInfo.sex,
      })
      this.$store.commit('user/SET_AVATAR', this.userData.avatar)
      this.$store.commit('user/SET_NICKNAME', this.userData.nickname);
      const isFixedVest = uni.getStorageSync("isFixedVest")
      if (!isFixedVest) {
        this.$store.commit('user/SET_AVATARIM', this.userData.avatar)
        this.$store.commit('user/SET_NICKNAMEIM', this.userData.nickname);
      }
      this.userData = null;
      this.editInfoModal = false
    },
    handleClick() {
      if (this.user.avatarIM === this.user.avatar) {
        this.userData = JSON.parse(JSON.stringify(this.user))
        this.editInfoModal = true
        return
      }
      EventBus.$emit(EventBus.vest)
    },
    /**
     * 解决安卓手机收起键盘input光标还在的问题
     */
    keyboardWatch() {
      if (
        document.activeElement.tagName === 'INPUT' ||
        document.activeElement.tagName === 'TEXTAREA'
      ) {
        const nowWindowHeight = window.innerHeight;
        if (nowWindowHeight === preWindowHeight) {
          this.$refs.inputRef.blur();
        }
      }
    },
    async showInput() {
      this.active = true;
      await this.$nextTick();
      this.$refs.inputRef.focus();
    },
    async blur() {
      setTimeout(() => {
        this.active = false;
      }, 200)

    },
    async send() {
      if (!this.content) {
        this.$toast('请输入内容');
        return;
      }
      this.$tim.updateUserInfo({ avatar: this.user.avatarIM, username: this.user.nicknameIM });
      const res = await this.$tim
        .sendMessage(this.mix_liveId, {
          content: this.content,
          sessionId: this.mix_sessionId,
          replyUserId: this.replyUserId,
          replyUsername: this.replyUsername,
          v: this.user.nickname !== this.user.nicknameIM ? 1 : 0,
        })
        .catch(err => {
          this.replyUserId = ''
          this.replyUsername = ''
          this.$toast(err.message);
        });
      if (!res) {
        return;
      }

      // 隐私设置开启
      if (this.mix_audiencePrivacyProtection) {
        res.avatar =
          'https://weilebo-img.oss-cn-hangzhou.aliyuncs.com/icon/bNRkecaeTykciCZaasC4SGSwPCCGTrXD.svg';
        res.username = formatUsername(res.username);
      }
      this.$emit('send', res);
      this.active = false;
      this.content = '';
      this.replyUserId = ''
      this.replyUsername = ''
    },
  },
};
</script>

<style lang="scss" scoped>
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-info {
  padding: 14px 16px 18px;
  width: 326px;


  .edit-info-title {
    font-weight: 600;
    font-size: 18px;
    color: #1D2129;
    line-height: 25px;
    text-align: center;
    margin-bottom: 24px;
  }

  .edit-info-item {
    height: 30px;
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #1D2129;
    line-height: 20px;

    img {
      width: 30px;
      height: 30px;
      border-radius: 30px;
    }
  }

  .edit-info-action {
    margin-top: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      width: 138px;
      height: 38px;
      background: #FFFFFF;
      border-radius: 23px;
      border: 1px solid #295EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: #295EFF;
      line-height: 24px;

      &:last-of-type {
        background: #295FFF;
        color: #fff;
      }

    }
  }
}

._comment-action {
  font-size: 14px;
}

._comment-action__kits {
  display: flex;
  align-items: center;
  padding: 10px;
}

._comment-action__kits-tip {
  flex: 1;
  height: 36px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  line-height: 36px;
  color: #fff;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 17px;

  img {
    width: 30px;
    height: 30px;
    border-radius: 30px;
    margin-right: 12px;
  }
}

._comment-action__kits-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  margin-left: 10px;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
}

._comment-action__kits-praise {
  background: rgba(0, 0, 0, 0.3);

  img {
    width: 20px;
  }
}

._comment-action__input {
  display: flex;
  padding: 10px;
  background: #fff;

  .van-field {
    flex: 1;
    height: 36px;
    padding: 5px 10px;
    background: rgba(0, 0, 0, 0.02);
    border-radius: 5px;
    outline: none;

    &::after {
      display: none;
    }

    ::v-deep input::placeholder {
      color: rgba(0, 0, 0, 0.3);
    }
  }

  .van-button {
    min-width: 60px;
    height: 36px;
    margin-left: 15px;
    border-radius: 5px;
  }
}
</style>
